// 模拟API客户端，用于开发和测试
import {
    Dataset,
    CreateDatasetRequest,
    UpdateDatasetRequest,
    DatasetStats
} from '@/types/dataset'
import { ImageData, ImageMetadata } from '@/types/image'
import {
    Task,
    TaskResult,
    TaskStatusInfo,
    TaskParams,
    CreateTaskRequest,
    UpdateTaskRequest
} from '@/types/task'
import { PaginatedResponse } from '@/types/api'
import { PaginationOption } from '@/types/common'
import { ExtendedApiClient } from './api'

// 模拟数据生成器
const generateMockImageData = (id: string, type: '2D' | '3D' = '3D'): ImageData => ({
    id,
    type,
    format: 'DICOM',
    dimensions: type === '3D'
        ? { width: 512, height: 512, depth: 100 }
        : { width: 1024, height: 1024 },
    pixelSpacing: [1.0, 1.0, 1.0],
    imageOrientation: [1, 0, 0, 0, 1, 0],
    imagePosition: [0, 0, 0],
    windowCenter: 400,
    windowWidth: 1600,
    pixelData: new ArrayBuffer(512 * 512 * (type === '3D' ? 100 : 1) * 2),
    metadata: {
        patientName: `测试患者_${id}`,
        patientId: `P${id.padStart(6, '0')}`,
        studyDate: '2024-01-01',
        studyTime: '120000',
        modality: type === '3D' ? 'CT' : 'CR',
        bodyPart: 'CHEST',
        manufacturer: 'Mock Medical Systems'
    },
    url: `/mock/images/${id}/data`,
    thumbnailUrl: `/mock/images/${id}/thumbnail`,
    createdAt: new Date(),
    updatedAt: new Date()
})

const generateMockDataset = (id: string, type: '2D' | '3D' = '3D'): Dataset => ({
    id,
    name: `${type === '3D' ? '胸部CT' : '胸部X光'}数据集_${id}`,
    description: `这是一个用于${type === '3D' ? '3D CT' : '2D X光'}影像分析的测试数据集`,
    type,
    tasks: [
        {
            id: `task_${id}_1`,
            name: '病灶检测',
            type: 'detection',
            description: '检测影像中的异常病灶',
            config: {
                parameters: { threshold: 0.5, maxDetections: 10 },
                modelEndpoint: '/models/detection'
            },
            status: 'idle',
            datasetId: id,
            createdAt: new Date(),
            updatedAt: new Date()
        },
        {
            id: `task_${id}_2`,
            name: '影像分类',
            type: 'classification',
            description: '对影像进行疾病分类',
            config: {
                parameters: { classes: ['normal', 'abnormal'] },
                modelEndpoint: '/models/classification'
            },
            status: 'idle',
            datasetId: id,
            createdAt: new Date(),
            updatedAt: new Date()
        }
    ],
    images: [
        generateMockImageData(`${id}_img_1`, type),
        generateMockImageData(`${id}_img_2`, type),
        generateMockImageData(`${id}_img_3`, type)
    ],
    imageCount: 3,
    size: 1024 * 1024 * 50, // 50MB
    tags: ['chest', 'medical', 'test'],
    isPublic: true,
    owner: 'test_user',
    createdAt: new Date(),
    updatedAt: new Date()
})

// 模拟数据存储
const mockDatasets: Dataset[] = [
    generateMockDataset('1', '3D'),
    generateMockDataset('2', '2D'),
    generateMockDataset('3', '3D'),
    generateMockDataset('4', '2D'),
    generateMockDataset('5', '3D')
]

// 模拟延迟函数
const delay = (ms: number = 500): Promise<void> =>
    new Promise(resolve => setTimeout(resolve, ms))

// 模拟API客户端实现
export const mockApi: ExtendedApiClient = {
    // 数据集相关
    async getDatasets(): Promise<Dataset[]> {
        await delay()
        return [...mockDatasets]
    },

    async getDataset(id: string): Promise<Dataset> {
        await delay()
        const dataset = mockDatasets.find(d => d.id === id)
        if (!dataset) {
            throw new Error(`Dataset with id ${id} not found`)
        }
        return { ...dataset }
    },

    async createDataset(data: CreateDatasetRequest): Promise<Dataset> {
        await delay()
        const newDataset = generateMockDataset(
            `mock_${Date.now()}`,
            data.type
        )
        newDataset.name = data.name
        newDataset.description = data.description
        newDataset.tags = data.tags || []
        newDataset.isPublic = data.isPublic || false

        mockDatasets.push(newDataset)
        return { ...newDataset }
    },

    async updateDataset(id: string, data: UpdateDatasetRequest): Promise<Dataset> {
        await delay()
        const datasetIndex = mockDatasets.findIndex(d => d.id === id)
        if (datasetIndex === -1) {
            throw new Error(`Dataset with id ${id} not found`)
        }

        const updatedDataset = {
            ...mockDatasets[datasetIndex],
            ...data,
            updatedAt: new Date()
        }
        mockDatasets[datasetIndex] = updatedDataset
        return { ...updatedDataset }
    },

    async deleteDataset(id: string): Promise<void> {
        await delay()
        const index = mockDatasets.findIndex(d => d.id === id)
        if (index === -1) {
            throw new Error(`Dataset with id ${id} not found`)
        }
        mockDatasets.splice(index, 1)
    },

    async getDatasetStats(id: string): Promise<DatasetStats> {
        await delay()
        const dataset = mockDatasets.find(d => d.id === id)
        if (!dataset) {
            throw new Error(`Dataset with id ${id} not found`)
        }

        return {
            totalImages: dataset.imageCount,
            totalSize: dataset.size,
            imageFormats: { 'DICOM': dataset.imageCount },
            modalities: { [dataset.type === '3D' ? 'CT' : 'CR']: dataset.imageCount },
            lastUpdated: dataset.updatedAt
        }
    },

    async getDatasetsWithPagination(pagination?: PaginationOption): Promise<PaginatedResponse<Dataset>> {
        await delay()
        const page = pagination?.page || 1
        const pageSize = pagination?.pageSize || 10
        const startIndex = (page - 1) * pageSize
        const endIndex = startIndex + pageSize

        const items = mockDatasets.slice(startIndex, endIndex)

        return {
            items,
            total: mockDatasets.length,
            page,
            pageSize,
            hasNext: endIndex < mockDatasets.length,
            hasPrev: page > 1
        }
    },

    // 影像数据相关
    async getImageData(imageId: string): Promise<ImageData> {
        await delay()
        // 查找包含该图像的数据集
        for (const dataset of mockDatasets) {
            const image = dataset.images.find(img => img.id === imageId)
            if (image) {
                return { ...image }
            }
        }
        throw new Error(`Image with id ${imageId} not found`)
    },

    async getImageMetadata(imageId: string): Promise<ImageMetadata> {
        await delay()
        const imageData = await this.getImageData(imageId)
        return imageData.metadata || {}
    },

    async uploadImages(datasetId: string, files: File[]): Promise<ImageData[]> {
        await delay(2000) // 模拟上传时间
        const dataset = mockDatasets.find(d => d.id === datasetId)
        if (!dataset) {
            throw new Error(`Dataset with id ${datasetId} not found`)
        }

        const uploadedImages = files.map((file, index) =>
            generateMockImageData(`${datasetId}_upload_${Date.now()}_${index}`, dataset.type)
        )

        dataset.images.push(...uploadedImages)
        dataset.imageCount += uploadedImages.length
        dataset.updatedAt = new Date()

        return uploadedImages
    },

    async deleteImages(imageIds: string[]): Promise<void> {
        await delay()
        for (const dataset of mockDatasets) {
            dataset.images = dataset.images.filter(img => !imageIds.includes(img.id))
            dataset.imageCount = dataset.images.length
        }
    },

    // 任务相关
    async getTasks(datasetId: string): Promise<Task[]> {
        await delay()
        const dataset = mockDatasets.find(d => d.id === datasetId)
        if (!dataset) {
            throw new Error(`Dataset with id ${datasetId} not found`)
        }
        return [...dataset.tasks]
    },

    async createTask(data: CreateTaskRequest): Promise<Task> {
        await delay()
        const newTask: Task = {
            id: `task_${Date.now()}`,
            name: data.name,
            type: data.type,
            description: data.description,
            config: data.config,
            status: 'idle',
            datasetId: data.datasetId,
            priority: data.priority || 1,
            createdAt: new Date(),
            updatedAt: new Date()
        }

        const dataset = mockDatasets.find(d => d.id === data.datasetId)
        if (dataset) {
            dataset.tasks.push(newTask)
        }

        return { ...newTask }
    },

    async updateTask(id: string, data: UpdateTaskRequest): Promise<Task> {
        await delay()
        for (const dataset of mockDatasets) {
            const taskIndex = dataset.tasks.findIndex(t => t.id === id)
            if (taskIndex !== -1) {
                const updatedTask = {
                    ...dataset.tasks[taskIndex],
                    ...data,
                    config: {
                        ...dataset.tasks[taskIndex].config,
                        ...data.config,
                        parameters: data.config?.parameters || dataset.tasks[taskIndex].config.parameters || {}
                    },
                    updatedAt: new Date()
                }
                dataset.tasks[taskIndex] = updatedTask
                return { ...updatedTask }
            }
        }
        throw new Error(`Task with id ${id} not found`)
    },

    async deleteTask(id: string): Promise<void> {
        await delay()
        for (const dataset of mockDatasets) {
            const taskIndex = dataset.tasks.findIndex(t => t.id === id)
            if (taskIndex !== -1) {
                dataset.tasks.splice(taskIndex, 1)
                return
            }
        }
        throw new Error(`Task with id ${id} not found`)
    },

    async startTask(taskId: string, params: TaskParams): Promise<TaskResult> {
        await delay(1000)

        // 模拟任务执行结果
        const mockResult: TaskResult = {
            id: `result_${Date.now()}`,
            taskId,
            status: 'success',
            data: {
                detections: [
                    {
                        id: 'det_1',
                        bbox: [100, 100, 50, 50],
                        confidence: 0.85,
                        class: 'nodule',
                        slice: 45
                    }
                ]
            },
            metrics: {
                accuracy: 0.92,
                precision: 0.88,
                recall: 0.90,
                f1Score: 0.89
            },
            executionTime: 120,
            createdAt: new Date()
        }

        return mockResult
    },

    async cancelTask(id: string): Promise<void> {
        await delay()
        // 在实际实现中，这里会更新任务状态为cancelled
        console.log(`Task ${id} cancelled`)
    },

    async getTaskStatus(taskId: string): Promise<TaskStatusInfo> {
        await delay()
        return {
            id: taskId,
            status: 'completed',
            progress: 100,
            message: 'Task completed successfully',
            currentStep: 'Finished',
            totalSteps: 5,
            startTime: new Date(Date.now() - 120000), // 2分钟前开始
            estimatedCompletion: new Date()
        }
    },

    async getTaskResults(taskId: string): Promise<TaskResult[]> {
        await delay()
        return [
            {
                id: `result_${taskId}_1`,
                taskId,
                status: 'success',
                data: {
                    detections: [
                        {
                            id: 'det_1',
                            bbox: [100, 100, 50, 50],
                            confidence: 0.85,
                            class: 'nodule'
                        }
                    ]
                },
                executionTime: 120,
                createdAt: new Date()
            }
        ]
    },

    async getTasksWithPagination(datasetId: string, pagination?: PaginationOption): Promise<PaginatedResponse<Task>> {
        await delay()
        const tasks = await this.getTasks(datasetId)
        const page = pagination?.page || 1
        const pageSize = pagination?.pageSize || 10
        const startIndex = (page - 1) * pageSize
        const endIndex = startIndex + pageSize

        const items = tasks.slice(startIndex, endIndex)

        return {
            items,
            total: tasks.length,
            page,
            pageSize,
            hasNext: endIndex < tasks.length,
            hasPrev: page > 1
        }
    },

    // 健康检查
    async healthCheck(): Promise<{ status: string; timestamp: string }> {
        await delay(100)
        return {
            status: 'healthy',
            timestamp: new Date().toISOString()
        }
    }
}

// 根据环境变量决定使用真实API还是模拟API
export const getApiClient = async (): Promise<ExtendedApiClient> => {
    if (process.env.NODE_ENV === 'development' && process.env.NEXT_PUBLIC_USE_MOCK_API === 'true') {
        console.log('Using mock API client for development')
        return mockApi
    }

    // 动态导入真实API客户端
    const { default: realApi } = await import('./api')
    return realApi
}

export default mockApi